var table = document.getElementById('shoppingCart');
var checkAll = document.getElementById('checkAll');
var options = document.getElementsByName('option');
var userId =function (){
  if(sessionStorage.getItem('loginUser')===null){
      return null;
  }  else{
      console.log(1111111)
      return JSON.parse(sessionStorage.getItem('loginUser')).userID;
  }
} ;
var testwww = null;
//头部显示地理位置和下拉框

window.onload = function (){
    if (null === userId()) {
        alert("请先登录！");
        window.location.href = backend + "login&register.html";

    }else{
        document.getElementById("page_login").innerHTML="欢迎 "
            + "<a class=\"pageullireg\">"+JSON.parse(sessionStorage.getItem('loginUser')).userInfo
            + "</a>&nbsp;";

    }
}
window.addEventListener('load', function () {


    // 显示我的当当下拉
    var pagelidd = document.querySelector('.pagelidd');
    var pageddul = document.querySelector('.pageddul');
    var pageliddimg = document.querySelector('.pageliddimg');
    pagelidd.onmouseover = function () {
        pageddul.style.display = 'block';
        pageliddimg.style.display = 'none';
    }
    pagelidd.onmouseout = function () {
        pageddul.style.display = 'none';
        pageliddimg.style.display = 'block';
    }
    // 企业采购
    var pagelicg = document.querySelector('.pagelicg');
    var pagecgul = document.querySelector('.pagecgul');
    var pagelicgimg = document.querySelector('.pagelicgimg');
    pagelicg.onmouseover = function () {
        pagecgul.style.display = 'block';
        pagelicgimg.style.display = 'none';
    }
    pagelicg.onmouseout = function () {
        pagecgul.style.display = 'none';
        pagelicgimg.style.display = 'block';
    }
});

// 加载购物车商品
fetch(backend + "shoppingCart/listCartItem?uid="+userId(),{
    method: 'get',
    })
    .then(function (dataJ) {
        data = dataJ.json().then((dataA) => {
            if(dataA.countNumber===0){
                $('input').remove();
                // let h2 = document.createElement("h2");
                // h2.innerText = "购物车为空！"
                table.childNodes[1].childNodes[0].innerHTML = '<h2 style="text-align: center">购物车为空</h2>'
            }else{
                data = dataA.resultMap;
                console.log(userId());
                // datalength = data.length
                let itemList = data;
                for (let i = 0; i < itemList.length; i++) {
                    itemInfo = itemList[i];
                    table.insertRow(1).insertCell(0).colspan = 7;
                    // table.children[0].attr("ff","ddddd")
                    tr = table.insertRow(1);
                    // console.log(tr.parentNode.nodeValue());
                    let bookInfo  = getBookByID(itemInfo.bookId);
                    console.log("binfo-main:"+itemInfo);
                    // testwww = tr;
                    // tr.parentNode.parent().css("background-color","red")
                    tr.insertCell(0).innerHTML = '<input type="checkbox" itemid="'+itemInfo.id+'" name="option" style="text-align: center;">'
                    tr.insertCell(1).innerHTML = '<dl><a href="'+backend+'commodityDetail.html?bookId='+itemInfo.bookId+'"><dt><img src=' +backend+ bookInfo.bookPicture + ' width="40px" height="40px"></dt><dd><p>' + bookInfo.bookName + '</p></dd></a></dl>';
                    tr.insertCell(2).innerHTML = bookInfo.bookPrice;
                    tr.insertCell(3).innerHTML = '<input type="button" itemid="'+itemInfo.id+'" value="-" onclick="sub(this)" style="width:60px">\
                                        <input type="text" name="count" value=" ' + itemInfo.num + ' " size="4" readonly="readonly">\
                                        <input type="button" value="+" itemid="'+itemInfo.id+'" onclick="add(this)"  style="width:60px">';
                    tr.insertCell(4).innerHTML = '<span>' + (bookInfo.bookPrice * itemInfo.num).toFixed(2) + '</span>';
                    tr.insertCell(5).innerHTML = '<input type="button" itemid="'+itemInfo.id+'" onclick="delItem(this)" value="删除">';
                    tr.insertCell(6).innerHTML = '<span hidden>' + itemInfo.bookId + '</span>';
                }
                // 绑定全选和单项选择事件
                checkAll.onclick = selectAll;
                for (let i = 0; i < options.length; i++) {
                    options[i].onclick = reCheck;
                }
                // 绑定删除按钮触发事件
                // for (let i = 2; i < table.childNodes[1].childNodes.length; i += 2) {
                //     let delBtn = table.childNodes[1].childNodes[i].cells[5].children[0];
                //     delBtn.onclick = function () {
                //         let tr = delBtn.parentNode.parentNode;
                //         let bookId = tr.cells[6].children[0].innerText;
                //         updateItem(bookId, 0);
                //         tr.parentNode.removeChild(tr.previousElementSibling)
                //         tr.parentNode.removeChild(tr)
                //         summerize();
                //         reCheck();
                //     }
                // }
                checkAll.checked = true;
                selectAll();
            }

        }).catch((err) => {
            console.log(err);
        })

    });

// 计算总价格
function summerize() {
    let totalPrice = 0;
    for (let i = 2; i < table.childNodes[1].childNodes.length; i += 2) {
        let option = table.childNodes[1].childNodes[i].cells[0].children[0];
        if (option.checked) {
            totalPrice += Number(table.childNodes[1].childNodes[i].cells[4].children[0].innerHTML);
        }
    }
    document.getElementById("total").innerHTML = totalPrice.toFixed(2);
}
function clearAll(){
    $.ajax({
        url:"shoppingCart/clearCart?uid="+userId(),
        success(dataJ){
            let data = JSON.parse(dataJ)
            alert(data.msg)
            location.reload()
        }
    })
}
function delItem(btn){
    let itemId = btn.attributes['itemid'].value - 0;
    // alert(itemId)
    $.ajax({
        url:backend+'/shoppingCart/removeFromCart',
        type:'POST',
        data:JSON.stringify({"itemId":itemId}),
        contentType : "application/json;charset=UTF-8",
        success(dataJ){
            let data = JSON.parse(dataJ)
            alert(data.msg)
            location.reload()
            // btn.parentNode.parentNode
        }
    })
}

function getBookByID(bookID){
    let bookInfoGet = null;
    $.ajax({
        url:backend+"/book/getBookByID?bookId="+bookID,
        async : false,
        contentType : "application/json;charset=UTF-8",
        success:function(dataJ){

            data = JSON.parse(dataJ)
            console.log(data.bookInfo);
            //将userId保存在本地
            if(data.status===true) {
                bookInfoGet = data.bookInfo;
            }
            //location.assign("shoppingCart.html");
        }
    })
    return bookInfoGet;
}


// 计算单组商品的价格
function summerizeSingle() {
    for (let i = 2; i < table.childNodes[1].childNodes.length; i += 2) {
        table.childNodes[1].childNodes[i].cells[4].childNodes[0].innerHTML = (table.childNodes[1].childNodes[i].cells[2].childNodes[0].textContent * table.childNodes[1].childNodes[i].cells[3].getElementsByTagName('input')[1].value).toFixed(2);
        // table.childNodes[1].childNodes[i].cells[3].children[0].innerHTML = (table.childNodes[1].childNodes[i].cells[2].innerHTML * table.childNodes[1].childNodes[i].cells[3].children[1].value).toFixed(2);
    }
}

//全选
function selectAll() {
    for (let i = 2; i < table.childNodes[1].childNodes.length; i += 2) {
        let option = table.childNodes[1].childNodes[i].cells[0].children[0];
        option.checked = checkAll.checked;
        // option.checked = checkAll;
    }
    summerize();
}

//反选
function reCheck() {
    let allChecked = true;
    for (let i = 0; i < options.length; i++) {
        if (!options[i].checked) {
            allChecked = false;
            break;
        }
    }
    if (allChecked) {
        checkAll.checked = true;
    } else {
        checkAll.checked = false;
    }
    summerize();
}

//减少商品数量
function sub(btn) {
    let num = btn.nextElementSibling;
    num.value--;
    if (num.value < 0) {
        num.value = 0;
    }
    summerizeSingle();
    summerize();
    // testwww = btn;
    console.log()

    // let tr = btn.parentNode.parentNode;
    // let bookId = tr.cells[6].children[0].innerText;
    updateItem(btn.attributes['itemid'], num.value);

}

// 增加商品数量
function add(btn) {
    let num = btn.previousElementSibling;
    num.value++;
    summerizeSingle();
    summerize();
    updateItem(btn.attributes['itemid'], num.value);
}

//删除选中的
function deleteChecked() {
    itemList = table.childNodes[1].childNodes;
    for (let i = itemList.length - 2; i > 0; i -= 2) {
        // table.childNodes[1].childNodes[48].cells[0].children[0].checked
        let option1 = itemList[i].cells[0].children[0];
        console.log(itemList)
        // table.childNodes[1].childNodes[2].cells[0].children[0].checked
        if (option1.checked) {
            // let tr = option.parentNode.parentNode;
            // let bookId = tr.cells[6].children[0].innerText;
            console.log(option1.attributes['itemid'])
            delItem(option1)
            // updateItem(option1.attributes['itemid'], 0);
            tr.parentNode.removeChild(tr.previousElementSibling);
            tr.parentNode.removeChild(tr);
            summerize();
            reCheck();
        }
    }
}

// 更新购物车单份商品到后台
function updateItem(itemId, num) {
    fetch(backend + "/shoppingCart/updateCartItem", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            "newCartItem":
                {
                    "id":itemId.value-0,
                    "num": num-0
                }
        }
        )
    });
}